package com.kma.ncpractice2013.dao;

import com.kma.ncpractice2013.model.PromoCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import org.springframework.jdbc.core.RowMapper;

/**
 *
 * @author Illya
 */
public class PromoCodeDAO extends DAO<PromoCode>
{
    
    public void create(PromoCode code)
    {
        String sql = "INSERT INTO PROMOCODE_TYPES(ID,CODE,TYPE_ID,MANAGER_ID) VALUES (?,?,?)";
        jdbcTemplate.update(sql, code.getId(),code.getCode(),
                            code.getTypeId(),code.getManagerId());
    }

    public void update(PromoCode code)
    {
        String sql = "UPDATE PROMOCODE_TYPES SET CODE = ?,TYPE_ID = ?,MANAGER_ID = ? WHERE ID = ?";
        jdbcTemplate.update(sql, code.getCode(),code.getTypeId(),code.getManagerId());
    }

    public PromoCode getById(int id)
    {
        List<PromoCode> codes;
        String sql = "SELECT * FROM PROMOCODE_TYPES WHERE ID = " + id;
        codes = jdbcTemplate.query(sql, new PromoCodeRowMapper());
        return codes.get(0);
    }

    public Collection<PromoCode> getAll()
    {
        String sql = "SELECT  * FROM PROMOCODE_TYPES ";
	    return jdbcTemplate.query(sql, new PromoCodeRowMapper());
    }

    public void deleteById(int id)
    {
        String sql = "DELETE FROM PROMOCODE_TYPES WHERE ID = " + id;
        jdbcTemplate.update(sql);
    }
    
    private static final class PromoCodeRowMapper implements RowMapper
    {
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException
        {
            PromoCode code = new PromoCode();
            code.setId(rs.getInt("id"));
            code.setManagerId(rs.getInt("manager_id"));
            code.setTypeId(rs.getInt("type_id"));
            code.setCode(rs.getString("code"));
            return code;
        }
    }
}
